<template>
  <a-modal :visible="visible" :footer="null" @cancel="toCloseModal">
    <a-form
      :model="formState"
      name="basic"
      :label-col="{ span: 8 }"
      :wrapper-col="{ span: 8 }"
      :rules="rules"
      autocomplete="off"
      @finish="onFinish"
    >
      <a-form-item label="用户名" name="username">
        <a-input v-model:value="formState.username" />
      </a-form-item>
      <a-form-item label="密码" name="password">
        <a-input-password v-model:value="formState.password" />
      </a-form-item>
      <a-form-item label="验证码" name="Captcha-Code">
        <VerificationCode
          v-model:value="formState['Captcha-Code']"
          v-model:key="formState['Captcha-Key']"
        />
      </a-form-item>
      <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
        <a-button type="primary" html-type="submit" :loading="loading">Submit</a-button>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { message } from 'ant-design-vue';
import VerificationCode from './VerificationCode.vue';
import type { VerificationType } from './VerificationCode.vue';

interface FormState extends VerificationType {
  username: string;
  password: string;
}
const rules = ref({
  username: [{ required: true, message: '请输入用户名' }],
  password: [{ required: true, message: '请输入密码' }],
  'Captcha-Code': [{ required: true, message: '请输入验证码' }],
});
const formState = reactive<FormState>({
  username: '',
  password: '',
  'Captcha-Code': '',
  'Captcha-Key': '',
});

/* 接收外部参数 */
interface PropsType {
  load: (params: any, header: any) => Promise<any>;
  visible: boolean;
}
const props = withDefaults(defineProps<PropsType>(), {
  load: undefined,
  visible: false,
});
const emits = defineEmits(['update:visible']);
const toCloseModal = () => {
  emits('update:visible', false);
};

/* 登陆 */
const loading = ref(false);
const onFinish = async (values: FormState) => {
  // if (props.load) { return false }
  try {
    const params = {
      username: values.username,
      password: values.password,
      grant_type: '',
      scope: 'all',
      tenantId: '000000',
    };
    loading.value = true;
    await props.load(params, {
      'Captcha-Key': formState['Captcha-Key'],
      'Captcha-Code': formState['Captcha-Code'],
    });
    message.success('登陆成功！');
    emits('update:visible', false);
  } finally {
    loading.value = false;
  }
};
</script>
